package com.piece.core.resource.support;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.log.client.dto.UserDTO;
import com.piece.core.log.config.UserContextHolder;
import com.piece.core.framework.support.dto.UserDetailDTO;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

public class CustomResourceServerTokenServices implements ResourceServerTokenServices {

    private final TokenStore tokenStore;

    public CustomResourceServerTokenServices(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
        if (null == tokenStore) {
            return null;
        }
        OAuth2Authentication authentication = tokenStore.readAuthentication(accessToken);
        if (null != authentication) {
            Object details = authentication.getUserAuthentication().getDetails();
            if (details instanceof UserDetailDTO) {
                UserDetailDTO user = (UserDetailDTO) details;
                UserContextHolder.set(new UserDTO(user.getId(), user.getUsername(), user.getAvatar(), user.permission(), user.getDeptId(), user.getDeptName()));
            }
        }

        return authentication;
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        throw new UnsupportedOperationException(I18nUtil.message(ExceptionConstants.PERMISSION));
    }
}
